package com.sen.service.impl;


import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sen.constant.StockConstant;
import com.sen.dao.StockheadDao;
import com.sen.entity.*;
import com.sen.service.DruginfoService;
import com.sen.service.StockService;
import com.sen.service.StockheadService;
import com.sen.service.SupplierService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service("stockheadService")
public class StockheadServiceImpl extends ServiceImpl<StockheadDao, StockheadEntity> implements StockheadService {

    @Autowired
    private StockService stockService;
    @Autowired
    private DruginfoService druginfoService;
    @Autowired
    private EmpServiceImpl empService;
    @Autowired
    private SupplierService supplierService;


    @Override
    public Page<StockheadEntity> queryAll(Map<String, String> stockheadMap) {

        //TODO 代码乱 需要整理，for循环是否可以修改成 stream 流

        //查询所有员工
        List<EmpEntity> empList = empService.list();

        //查询所有订单
        QueryWrapper<StockheadEntity> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(stockheadMap.get("state")))
            wrapper.eq("state", stockheadMap.get("state"));
        //根据订单号查询
        if (!StringUtils.isEmpty(stockheadMap.get("hno")))
            wrapper.eq("hno", stockheadMap.get("hno"));
        //给查看采购订单页面添加谁登陆查看谁的采购项
        QueryWrapper<StockheadEntity> queryWrapper = new QueryWrapper<>();
        if (stockheadMap.get("state").equals(StockConstant.StateEnum.STATE_SEND_BACK.getCode())) {
            queryWrapper.eq("seid", stockheadMap.get("eid"));
            queryWrapper.orderByDesc("idate");
        }
        if (!StringUtils.isEmpty(stockheadMap.get("getState")))
            queryWrapper.eq("state", stockheadMap.get("getState"));
        if (!StringUtils.isEmpty(stockheadMap.get("hno")))
            queryWrapper.eq("hno", stockheadMap.get("hno"));
        String begin = stockheadMap.get("createdate[0]");
        String end = stockheadMap.get("createdate[1]");
        //有值为true
        if ((StringUtils.hasText(begin) || begin != null) && (StringUtils.hasText(end) || end != null)) {
            queryWrapper.between("idate", begin, end);
        }
        //根据名称查询
        if (!StringUtils.isEmpty(stockheadMap.get("name"))) {
            //状态为空查询所有
            if (StringUtils.isEmpty(stockheadMap.get("state"))) {
                for (EmpEntity empEntity : empList) {
                    if (empEntity.getName().equals(stockheadMap.get("name"))) {
                        wrapper.eq("seid", empEntity.getEid()).or().eq("eid", empEntity.getEid());
                    }
                }
            }
            //判断状态是审核
            if (stockheadMap.get("state").equals(StockConstant.StateEnum.STATE_SEND_BACK.getCode())) {
                for (EmpEntity empEntity : empList) {
                    if (empEntity.getName().equals(stockheadMap.get("name"))) {
                        queryWrapper.eq("eid", empEntity.getEid());
                        queryWrapper.orderByDesc("idate");
                    }
                }
            }
            //申请人
            if (stockheadMap.get("state").equals(StockConstant.StateEnum.STATE_UNDER_REVIEW.getCode())) {
                for (EmpEntity empEntity : empList) {
                    if (empEntity.getName().equals(stockheadMap.get("name")))
                        wrapper.eq("seid", empEntity.getEid());
                }
            }
        }
        wrapper.orderByDesc("idate");

        //获取分页对象
        Page<StockheadEntity> page = new Page<>(Long.parseLong(stockheadMap.get("page")), Long.parseLong(stockheadMap.get("size")));
        Page<StockheadEntity> stockheadEntityPage = null;
        //判断是不是状态为2的
        if (stockheadMap.get("state").equals(StockConstant.StateEnum.STATE_SEND_BACK.getCode())) {
            stockheadEntityPage = this.baseMapper.selectPage(page, queryWrapper);
        } else {
            stockheadEntityPage = this.baseMapper.selectPage(page, wrapper);
        }
        //取出所有的值
        List<StockheadEntity> stockheadEntities = stockheadEntityPage.getRecords();

        //设置订单头
        for (StockheadEntity stockheadEntity : stockheadEntities) {
            //订单详情
            List<StockEntity> stockEntities = stockService.list(new QueryWrapper<StockEntity>().eq("hno", stockheadEntity.getHno()));
            if (!StringUtils.isEmpty(stockheadMap.get("state"))) {
                //判断状态是申请人
                if (stockheadMap.get("state").equals(StockConstant.StateEnum.STATE_UNDER_REVIEW.getCode())) {
                    //获取员工信息
                    EmpEntity empEntity = empService.getById(stockheadEntity.getSeid());
                    stockheadEntity.setSname(empEntity.getName());
                }
                //判断状态是审核
                if (stockheadMap.get("state").equals(StockConstant.StateEnum.STATE_SEND_BACK.getCode())) {
                    //审核人

                    EmpEntity empEntity = empService.getById(stockheadEntity.getEid());
                    if (empEntity != null)
                        stockheadEntity.setSname(empEntity.getName());
                }
            } else {
                if (empList != null) {
                    for (EmpEntity empEntity : empList) {
                        if (stockheadEntity.getSeid().equals(empEntity.getEid()))
                            stockheadEntity.setSname(empEntity.getName());
                        if (stockheadEntity.getEid().equals(empEntity.getEid()))
                            stockheadEntity.setEname(empEntity.getName());
                    }
                }
            }

            //遍历订单详情
            for (StockEntity stockEntity : stockEntities) {
                //获取药品信息
                DruginfoEntity druginfoEntity = druginfoService.getById(stockEntity.getDid());
                if (StringUtils.isEmpty(druginfoEntity)) throw new RuntimeException("药品信息");
                stockEntity.setMname(druginfoEntity.getMname());
                //获取生产厂家名称
                SupplierEntity supplierEntity = supplierService.getById(stockEntity.getSid());
                if (StringUtils.isEmpty(supplierEntity)) throw new RuntimeException("生产地为空");
                stockEntity.setSname(supplierEntity.getSname());
            }
            stockheadEntity.setChildren(stockEntities);
        }

        //把修改过的值赋值回page
        stockheadEntityPage.setRecords(stockheadEntities);

        return stockheadEntityPage;
    }

    //重新生成订单
    @Override
    public void anewStock(StockheadEntity stockheadEntities) {
        //查出对应订单号的所有详情
        boolean remove = stockService.remove(new QueryWrapper<StockEntity>().eq("hno", stockheadEntities.getHno()));
        //删除成功插入数据
        if (remove) {
            stockService.saveBatch(stockheadEntities.getChildren());
        }
        //修改表头信息
        stockheadEntities.setState(StockConstant.StateEnum.STATE_UNDER_REVIEW.getState());
        stockheadEntities.setRemark("");
        this.baseMapper.updateById(stockheadEntities);

    }

    @Override
    public Map<String, Object> getDataSta(String begin, String end) {

        //根据条件查询对应数据
        QueryWrapper<StockheadEntity> wrapper = new QueryWrapper<>();
        wrapper.between("idate", begin, end);
        wrapper.select("idate", "sum(money) money");
        wrapper.groupBy("DATE_FORMAT(idate,'%Y-%m-%d')");
        wrapper.orderByAsc("idate");
        List<StockheadEntity> stockheadEntities = baseMapper.selectList(wrapper);

        //因为返回有两部分数据：日期和日期对应金额
        //前端要数组json结构 对应java代码时list集合
        //创建两个list集合，一个是日期list 一个是价格list
        List<String> idate = new ArrayList<>();
        List<Double> priceDataList = new ArrayList<>();

        for (StockheadEntity stockheadEntity : stockheadEntities) {
            Date date = new Date(stockheadEntity.getIdate().toString());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            idate.add(sdf.format(date));
            priceDataList.add(stockheadEntity.getMoney());
        }

        //把封装之后的两个list集合放到map中返回
        Map<String, Object> map = new HashMap<>();
        map.put("idate", idate);
        map.put("priceDataList", priceDataList);

        return map;
    }
}

